//
//  CityVC.m
//  ImGuider
//
//  Created by 李陆涛 on 2017/12/12.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "CityVC.h"
#import "MapVC.h"
#import "CityTourCardVC.h"
#import "ScenicSpotViewController.h"
#import "GuiderListVC.h"
#import "IGMenuView.h"
#import "ShowAllHeadView.h"
#import "HomeHotCell.h"
#import "GuiderNodeCell.h"
#import "CityTourListVC.h"
#import "ScenicNodeVC.h"
#import "SpecialDetailVC.h"
#import "AllSearchVC.h"
#import "WeatherCarouselView.h"
#import "ScenicDescribeVC.h"

#import "SpecialListVC.h"
#import "JMHoledView.h"
#import "TabItem.h"

#import "RaidersListVC.h"
#import "RecommendMerchantCell.h"
#import "TickectVC.h"
#import "TickectDetailVC.h"
//#import "TicketCell.h"
#import "CityNearCell.h"

#import "AllMerchantVC.h"

#define mutby 9 / 16.0

#define HeaderViewHeight (kScreenWidth * mutby) + 100
@interface CityVC () <UITableViewDelegate, UITableViewDataSource,IGMenuViewDelegate,ShowAllHeadViewDelegate,AllSearchVCDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) UIImageView *cityImageView;
@property (nonatomic, strong) UILabel *cityNameLabel;
@property (nonatomic, strong) WeatherCarouselView *weatherView;

@property (nonatomic, strong) IGMenuView * menuView;

@property (nonatomic, strong) City *city;
@property (nonatomic, strong) NSArray *typeArray;
@end

@implementation CityVC


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTableView];
    
    [self setupHeadView];
    
    [self loadData];
    
//    if (self.tabBarController.selectedIndex == 1) {
//
//        self.rt_disableInteractivePop = YES;
//    }
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (self.tabBarController.selectedIndex == 1 && self.city) {
        
        [AppManager sharedManager].lastCity = self.city;
    }
}

- (void)setupHeadView {
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, HeaderViewHeight) ];
    
    self.cityImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth * mutby)];
    self.cityImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.cityImageView.image = [UIImage imageNamed:@"placeholder_rec"];
    self.cityImageView.clipsToBounds = YES;
    
    [headView addSubview:self.cityImageView];
    
    self.menuView = [[IGMenuView alloc] initWithFrame:CGRectMake(0, HeaderViewHeight - 100, kScreenWidth, 100)];
    self.menuView.showsHorizontalScrollIndicator = NO;
    
    self.menuView.igDelegate = self;
    
    [headView addSubview:self.menuView];
    
    self.tableView.tableHeaderView = headView;
    
    UIView *mengbanView = [UIView new];
    mengbanView.backgroundColor = kMengBanColor;
    
    [self.cityImageView addSubview:mengbanView];
    [mengbanView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.cityImageView);
    }];
    self.cityNameLabel = [UILabel new];
    self.cityNameLabel.font = FontBold(30);
    self.cityNameLabel.textColor = [UIColor whiteColor];
    [self.cityImageView addSubview:self.cityNameLabel];
    
    [self.cityNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.view.mas_left).offset(16);
        make.centerY.equalTo(self.cityImageView.mas_bottom).offset(-kScreenWidth * mutby / 2);;
        
    }];
    
    self.weatherView = [[WeatherCarouselView alloc] initWithFrame:CGRectMake(0, 0, 120, 60)];
    [self.cityImageView addSubview:self.weatherView];
    
    [self.weatherView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.cityNameLabel.mas_bottom).offset(5);
        make.leading.equalTo(self.cityNameLabel.mas_leading);
        make.width.mas_equalTo(kScreenWidth - 32);
        make.height.mas_equalTo(60);
        
    }];
    
    [self closeAutomaticallyAdjustsScrollViewInsets:self.tableView];
    self.barBGAlpha =  0;
    self.customBarStyle = UIStatusBarStyleLightContent;
}

- (void)setupTableView {
    
    // UIBarButtonItem * item = [UIBarButtonItem ]
    //
    
    // [self leftBarButton1WithImageName:@"back" selector1:@selector(goBack) button2ImageName:(NSString *)@"searchIcon" selector2:@selector(goSearchAction)];
    
    [self setAutoRowHeight:self.tableView];
    self.tableView.backgroundColor = kBGColor;
    
//    [self registCells:@[@"TicketCell"] tableView:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeHotCell" bundle:nil] forCellReuseIdentifier:[NSString stringWithFormat:@"HomeHotCell%d",(int)HomeCellTypeLine]];
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeHotCell" bundle:nil] forCellReuseIdentifier:[NSString stringWithFormat:@"HomeHotCell%d",(int)HomeCellTypeScenic]];
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeHotCell" bundle:nil] forCellReuseIdentifier:[NSString stringWithFormat:@"HomeHotCell%d",(int)HomeCellTypeSpecial]];
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeHotCell" bundle:nil] forCellReuseIdentifier:[NSString stringWithFormat:@"HomeHotCell%d",(int)HomeCellTypeTiket]];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendMerchantCell" bundle:nil] forCellReuseIdentifier:@"RecommendMerchantCell"];
    
    [self barItemWithImageNameArray:@[@"back",@"搜索"] selArray:@[@"goBack",@"goSearchAction"] isLeft:YES];
    
    
    //[self closeAutomaticallyAdjustsScrollViewInsets:self.tableView];
}

- (void)loadData {
    
    //    self.menuView.tabArray = @[@"map",@"view",@"line",@"guide",@"ticket",@"stragegy"];
    self.menuView.backgroundColor = [UIColor whiteColor];
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:[UIColor whiteColor]];
    @weakify(self);
    [NetAPIManager getCityDetail:self.cid block:^(City *city, NSError *error) {
        
        @strongify(self);
        
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        self.city = city;
        
        self.cityNameLabel.text = self.city.smartName;
        self.weatherView.weatherArray = city.weather;
        [self.cityImageView setImageURL:[NSURL URLWithString:city.pictureArray.firstObject] placeholderImage:kPlaceholderRec];
        self.menuView.tabArray = city.tagsArray;
        
        [self setupTypeArray];
        
        if (self.tabBarController.selectedIndex == 1) {
            [AppManager sharedManager].lastCity = city;
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self newGuidePage];
        });
        
    }];
}

- (void)setupTypeArray {
    
    NSMutableArray *typeArray = [NSMutableArray array];
    
    if (self.city.views.count > 0) {
        [typeArray addObject:@(HomeCellTypeScenic)];
    }
    if (self.city.customlines.count > 0) {
        [typeArray addObject:@(HomeCellTypeLine)];
    }
    if (self.city.albums.count > 0) {
        [typeArray addObject:@(HomeCellTypeSpecial)];
    }
    
    if ([AppManager sharedManager].hasTicket) {
        
        if (self.city.tickets.count > 0) {
            [typeArray addObject:@(HomeCellTypeTiket)];
        }
    }
    
    if (self.city.business.count > 0) {
        
        [typeArray addObject:@(CityCellTypeNear)];
    }
    
    self.typeArray = typeArray;
    
    [self.tableView reloadData];
}

- (void)goBack{
    
    [self.navigationController popViewControllerAnimated:YES];
    
    if (self.tabBarController.selectedIndex == 1) {
        [AppManager sharedManager].lastCity = nil;
    }
    
}
- (void)goSearchAction {
    
    AllSearchVC * vc = [[AllSearchVC alloc] init];
    
    vc.delegate = self;
    vc.hidesBottomBarWhenPushed = YES;
//    RTRootNavigationController * nav = [[RTRootNavigationController alloc] initWithRootViewController:vc];
//    [self presentViewController:nav animated:YES completion:nil];
    
    [self.navigationController pushViewController:vc animated:YES];
}

//新手引导
- (void)newGuidePage {
    
    if (!self.city) {
        return;
    }
    
    NSMutableDictionary *tabDict = [NSMutableDictionary dictionaryWithDictionary:@{ @"line":@{@"title":@"HOMEPAGE_CITYTOUR",@"imageName":@"urbanline",@"selectedNum":@(CityTourItem)}, @"guide":@{@"title":@"HOMEPAGE_GUIDER",@"imageName":@"tourguide",@"selectedNum":@(GuiderItem)}}];
    
    
    BOOL hasShowLine = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasShowLine"];
    BOOL hasShowGuider = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasShowGuider"];
    
    if (![self.city.tagsArray containsObject:@"line"]|| hasShowLine) {
        [tabDict removeObjectForKey:@"line"];
    }
    
    if (hasShowGuider) {
        
        [tabDict removeObjectForKey:@"guide"];
    }
    
    if (tabDict.count == 0) {
        
        return;
    }
    
    //添加遮罩指示
    JMHoledView *holedView = [[JMHoledView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view.window addSubview:holedView];
    
    [self addHoledView:holedView dict:tabDict];
    
    [holedView clickedBlock:^(JMHoledView *holedView, NSInteger index) {
        
        [holedView removeFromSuperview];
    }];
}

- (NSInteger)addHoledView:(JMHoledView *)holedView dict:(NSMutableDictionary *)tabDict {
    
    UIWindow * window = self.view.window;
    
    for (TabItem *item in self.menuView.subviews) {
        
        if (![item isKindOfClass:[TabItem class]]) {
            continue;
        }
        
        if ((item.selectNum == CityTourItem && [tabDict.allKeys containsObject:@"line"])) {
            CGRect rect = [item convertRect:item.bounds toView:self.view];
            TabItem *myItem = [TabItem initTabItemWith:tabDict[@"line"]];
            myItem.isHot = item.isHot;
            myItem.Ratio = item.Ratio;
            [myItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [holedView addHCustomView:myItem onRect:rect];
            
            UIImage *guideImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_HOME_CITY_TOUR", nil)];
            
            UIImageView *imageview = [[UIImageView alloc] initWithImage:guideImage];
            
            CGRect guideRect = CGRectMake(CGRectGetMaxX(rect) - (guideImage.size.width / 2), CGRectGetMinY(rect) - guideImage.size.height, guideImage.size.width, guideImage.size.height);
            
            CGFloat maxX = CGRectGetMaxX(guideRect);
            
            if (maxX >= (kScreenWidth - 16)) {
                
                guideRect.origin.x -= (maxX - (kScreenWidth - 16));
            }
            
            [holedView addHCustomView:imageview onRect:guideRect];
            [tabDict removeObjectForKey:@"line"];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasShowLine"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        } else if (item.selectNum == GuiderItem && [tabDict.allKeys containsObject:@"guide"]) {
            
            CGRect rect = [item convertRect:item.bounds toView:window];
            TabItem *myItem = [TabItem initTabItemWith:tabDict[@"guide"]];
            myItem.isHot = item.isHot;
            myItem.Ratio = item.Ratio;
            [myItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [holedView addHCustomView:myItem onRect:rect];
            
            UIImage *guideImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_HOME_GUIDER", nil)];
            
            UIImageView *imageview = [[UIImageView alloc] initWithImage:guideImage];
            
            CGRect guideRect = CGRectMake(CGRectGetMinX(rect) - (guideImage.size.width / 2), CGRectGetMaxY(rect) + 10, guideImage.size.width, guideImage.size.height);
            
            [holedView addHCustomView:imageview onRect:guideRect];
            [tabDict removeObjectForKey:@"guide"];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasShowGuider"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }
    return 0;
}


#pragma mark   -- AllSearchVCDelegate

- (void)selectModel:(SearchResultModel *)model {
    
    if ([model.type isEqualToString:@"view"]) {
        
        ScenicDescribeVC *scenicDesVC = [ScenicDescribeVC new];
        
        scenicDesVC.hidesBottomBarWhenPushed = YES;
        scenicDesVC.scenicid = model.ID;
        
        [self.navigationController pushViewController:scenicDesVC animated:YES];
    }else if([model.type isEqualToString:@"city"]){
        
//        self.cid = model.ID;
//        [self loadData];
        CityVC * cityVC = [[CityVC alloc] init];
        
        cityVC.hidesBottomBarWhenPushed = YES;
        
        cityVC.cid = model.ID;
        
        [self.navigationController pushViewController:cityVC animated:YES];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat yOffset = self.tableView.contentOffset.y;
    CGFloat H = kScreenWidth * mutby;
    if (yOffset <= 0) {
        
        CGFloat factor = -yOffset + H ;
        CGRect f = CGRectMake(- (kScreenWidth * factor/H - kScreenWidth)/2, yOffset, kScreenWidth *factor/H, factor);
        self.cityImageView.frame = f;
    }
    
    if (yOffset < (H - kNavigationBarHeight)) {
        
        CGFloat aplha = yOffset /(H -kNavigationBarHeight);
        
        self.barBGAlpha = aplha;
    }else {
        self.barBGAlpha = 1;
    }
    
    if (self.barBGAlpha > 0.8) {
        self.customBarStyle = UIStatusBarStyleDefault;
        self.title = self.city.smartName;
    } else {
        self.customBarStyle = UIStatusBarStyleLightContent;
        self.title = @"";
    }
}
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.typeArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    HomeCellType type = [self.typeArray[section] integerValue];

    if (type == CityCellTypeNear) {

        return self.self.city.business.count;
    }
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HomeCellType type = [self.typeArray[indexPath.section] integerValue];
    
//    if (type == HomeCellTypeTiket) {
//        TicketCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TicketCell"];
//        cell.ticket = self.city.tickets[indexPath.row];
//
//        return cell;
//    }
    
    if (type == CityCellTypeNear) {
        
        RecommendMerchantCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendMerchantCell"];
        MerchantModel *model = self.city.business[indexPath.row];
        cell.superVC = self;
        cell.model = model;
        
        return cell;
    }
    
    
    NSString *idf = [NSString stringWithFormat:@"HomeHotCell%d",(int)type];
    
    HomeHotCell *cell = [tableView dequeueReusableCellWithIdentifier:idf];
    
    cell.type = type;
    
    if (type == HomeCellTypeScenic) {
        cell.dataSource = self.city.views;
    } else if (type == HomeCellTypeLine) {
        cell.dataSource = self.city.customlines;
    } else if (type == HomeCellTypeSpecial) {
        cell.dataSource = self.city.albums;
    } else if (type == HomeCellTypeTiket) {
        
        cell.dataSource = self.city.tickets;
    }
    
    cell.superVC = self;
    
    return cell;
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    
//    HomeCellType type = [self.typeArray[indexPath.section] integerValue];
//    
//    if (type == HomeCellTypeTiket) {
//        
//        TicketModel * ticket = self.city.tickets[indexPath.row];
//        TickectDetailVC * vc = [[TickectDetailVC alloc] init];
//        vc.ticketID = ticket.tid;
//        vc.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:vc animated:YES];
//    }
//}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    HomeCellType type = [self.typeArray[section] integerValue];
    
    ShowAllHeadView *headview = [ShowAllHeadView getHeadViewWithTableView:tableView];
    headview.delegate = self;
    
    headview.type = type;
    return headview;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 60;
}

#pragma mark -- IGMenuViewDelegate

- (void)selecteItem:(SelectedNum)selectedNum {
    
    switch (selectedNum) {
        case MapItem:
        { // 地图
            
            MapVC *mapVC = [MapVC new];
            mapVC.city = self.city;
            mapVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mapVC animated:YES];
        }
            break;
        case CityTourItem:
        {// 主题线路
            CityTourListVC *vc = [CityTourListVC new];
            vc.city = self.city;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
            
            //            CityTourCardVC *cityTourVC = [CityTourCardVC new];
            //            cityTourVC.cityID = @(11);
            
        }
            break;
        case ScenicItem:
        {// 景点
            
            ScenicNodeVC *scenicVC = [ScenicNodeVC new];
            scenicVC.city = self.city;
            scenicVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:scenicVC animated:YES];
        }
            break;
        case TicketsItem:
            
        {
            TickectVC * vc = [[TickectVC alloc] init];
            
            vc.cityID = self.cid;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case RaidersItem:
        {
            RaidersListVC * raiderVC = [[RaidersListVC alloc] init];
            raiderVC.currentCityID = self.city.cid;
            
            raiderVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:raiderVC animated:YES];
        }
            
            break;
        case GuiderItem:
        { // 行家
            
            GuiderListVC *guiderVC = [GuiderListVC new];
            guiderVC.city = self.city;
            guiderVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:guiderVC animated:YES];
            
        }
            break;
        case BusinessItem: { // 商户
            
            AllMerchantVC * vc = [[AllMerchantVC alloc] init];
            vc.cityid = self.city.cid.stringValue;
            
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            
            
            break;
    }
}


#pragma mark- headview delegate
- (void)showAllAction:(ShowAllHeadView *)tableHeadView {
    
    HomeCellType type = tableHeadView.type;
    
    switch (type) {
        case HomeCellTypeLine: {
            
            CityTourListVC *vc = [CityTourListVC new];
            vc.isPopular = YES;
            vc.city = self.city;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case HomeCellTypeScenic: {
            
            ScenicNodeVC *scenicVC = [ScenicNodeVC new];
            scenicVC.city = self.city;
            scenicVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:scenicVC animated:YES];
        }
            break;
        case HomeCellTypeTiket: {
            
            TickectVC * vc = [[TickectVC alloc] init];
            vc.cityID = self.cid;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case HomeCellTypeSpecial: {
            
            SpecialListVC *vc = [SpecialListVC new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case CityCellTypeNear:{
            
            AllMerchantVC * vc = [[AllMerchantVC alloc] init];
            vc.cityid = self.city.cid.stringValue;
            
            vc.hidesBottomBarWhenPushed = YES;
             [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
}
@end

